package cn.dankal.flyaudio.store;

import android.content.DialogInterface;
import android.content.Intent;
import android.view.View;
import android.widget.TextView;

import com.classic.common.MultipleStatusView;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.kongzue.dialog.v2.SelectDialog;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import cn.dankal.basiclib.DKUserManager;
import cn.dankal.basiclib.base.activity.BaseActivity;
import cn.dankal.basiclib.pojo.ShopCarEntity;
import cn.dankal.basiclib.pojo.req.ShoppingCarItemReq;
import cn.dankal.basiclib.util.ToastUtils;
import cn.dankal.flyaudio.R;
import cn.dankal.flyaudio.adapter.ShoppingProductAdapter;
import cn.dankal.flyaudio.configs.LiveDataBusConstant;
import cn.dankal.flyaudio.contract.ShopCarContract;
import cn.dankal.flyaudio.entity.ShoppingOrderEntity;
import cn.dankal.flyaudio.presenter.ShopCarPresenter;

public class ShoppingCarActivity extends BaseActivity implements ShopCarContract.View {

    private RecyclerView productList;

    private ShoppingProductAdapter adapter;

    private TextView sales;

    private TextView amountView;

    private TextView editTextView;

    private MultipleStatusView statusView;

    private View pickAllView;
    private ShopCarPresenter presenter;

    private double amount = 0;
    private int count = 0;

    private boolean isEditStatus = false;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_shopping_car;
    }

    @Override
    protected void initComponents() {
        productList = findViewById(R.id.rv_shopping_product);
        statusView = findViewById(R.id.multiple_status_view);
        amountView = findViewById(R.id.tv_amount);
        sales = findViewById(R.id.tv_sales);
        editTextView = findViewById(R.id.tv_edit);
        TextView scoreView = findViewById(R.id.tv_score);
        LiveEventBus.get("create_order_success", String.class)
                .observe(this, new Observer<String>() {
                    @Override
                    public void onChanged(String s) {
                        adapter.clearAll();
                        presenter.getMyShopCar();
                    }
                });
        if (DKUserManager.isLogined()) {
            scoreView.setText("我的积分：" + DKUserManager.getUserScores().getUsable());
        } else {
            scoreView.setText("未登录");
        }
        presenter = new ShopCarPresenter();
        findViewById(R.id.iv_onback).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        presenter.attachView(this);
        adapter = new ShoppingProductAdapter();
        productList.setLayoutManager(new LinearLayoutManager(this));
        productList.setAdapter(adapter);
        sales.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<ShopCarEntity> shopCarEntities = adapter.getSelectProduct();
                if (isEditStatus) {
                    //删除
                    if (shopCarEntities.isEmpty()) {
                        ToastUtils.showShort("请选择要删除的商品");
                        return;
                    }
                    SelectDialog.show(ShoppingCarActivity.this, "提示", "是否要删除", "确定", (dialog, which) -> {
                        StringBuilder uuid = new StringBuilder();
                        for (ShopCarEntity entity : shopCarEntities) {
                            uuid.append(entity.getItemUuid());
                            uuid.append(",");
                        }
                        uuid.deleteCharAt(uuid.length() - 1);
                        presenter.deleteProduct(uuid.toString());
                    }, "取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    });
                } else {
                    if (shopCarEntities.isEmpty()) {
                        ToastUtils.showShort("请选择要结算的商品");
                        return;
                    }
                    List<ShoppingCarItemReq> req = new ArrayList<>();
                    for (ShopCarEntity entity : shopCarEntities) {
                        ShoppingCarItemReq shoppingCarItemReq = new ShoppingCarItemReq();
                        shoppingCarItemReq.setItemUuid(entity.getItemUuid());
                        shoppingCarItemReq.setItemCount(entity.getItemCount() + "");
                        req.add(shoppingCarItemReq);
                    }
                    ShoppingOrderEntity shoppingOrderEntity = new ShoppingOrderEntity();
//                    shoppingOrderEntity.setProducts(shopCarEntities);
                    shoppingOrderEntity.setItemReq(req);
                    Intent intent = new Intent(ShoppingCarActivity.this, ConfirmOrderActivity.class);
                    intent.putExtra("products", shoppingOrderEntity);
                    startActivity(intent);
                }

            }
        });
        editTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isEditStatus) {
                    editTextView.setText("取消");
                    isEditStatus = true;
                    sales.setBackgroundColor(getResources().getColor(R.color.color_E96056));
                    sales.setText("删除（" + count + "）");
                } else {
                    editTextView.setText("编辑");
                    isEditStatus = false;
                    sales.setBackgroundColor(getResources().getColor(R.color.color_0085B4));
                    sales.setText("结算（" + count + "）");
                }
            }
        });
        pickAllView = findViewById(R.id.ll_pick_all);
        pickAllView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (pickAllView.isSelected()) {
                    pickAllView.setSelected(false);
                    adapter.clearAll();
                } else {
                    pickAllView.setSelected(true);
                    adapter.pickAll();
                }
            }
        });
        LiveEventBus.get(LiveDataBusConstant.PICK_SHOPPING_CAR, String.class).observe(this, new Observer<String>() {
            @Override
            public void onChanged(String shopCarEntity) {
                if (adapter.getSelectProduct().size() == adapter.getDatas().size()) {
                    pickAllView.setSelected(true);
                } else {
                    pickAllView.setSelected(false);
                }
                getPrice();
            }
        });
        LiveEventBus.get(LiveDataBusConstant.DELETE_PRODUCT_NUM, ShopCarEntity.class).observe(this, new Observer<ShopCarEntity>() {
            @Override
            public void onChanged(ShopCarEntity shopCarEntity) {
                getPrice();
                presenter.deleteProduct(shopCarEntity.getItemUuid(), shopCarEntity.getItemCount() + "");
            }
        });
        LiveEventBus.get(LiveDataBusConstant.CHANGE_PRODUCT_NUM, ShopCarEntity.class).observe(this, new Observer<ShopCarEntity>() {
            @Override
            public void onChanged(ShopCarEntity shopCarEntity) {
                getPrice();
                presenter.deleteProduct(shopCarEntity.getItemUuid(), shopCarEntity.getItemCount() + "");
            }
        });
        LiveEventBus.get(LiveDataBusConstant.ADD_PRODUCT_NUM, ShopCarEntity.class).observe(this, new Observer<ShopCarEntity>() {
            @Override
            public void onChanged(ShopCarEntity shopCarEntity) {
                getPrice();
                presenter.deleteProduct(shopCarEntity.getItemUuid(), shopCarEntity.getItemCount() + "");
            }
        });
        LiveEventBus.get(LiveDataBusConstant.DELETE_SHOPPING_PRODUCT, ShopCarEntity.class).observe(this, new Observer<ShopCarEntity>() {
            @Override
            public void onChanged(ShopCarEntity shopCarEntity) {
                SelectDialog.show(ShoppingCarActivity.this, "提示", "是否要删除", "确定", (dialog, which) -> {
                    presenter.deleteProduct(shopCarEntity.getItemUuid());

                }, "取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
            }
        });
        statusView.showLoading();
        statusView.setOnRetryClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (v.getId() == R.id.empty_retry_view) {
                    finish();
                    return;
                }
                statusView.showLoading();
                presenter.getMyShopCar();
            }
        });
        presenter.getMyShopCar();
    }

    @Override
    protected void onDestroy() {
        presenter.detachView();
        super.onDestroy();
    }

    @Override
    public void hasNetWork() {
        super.hasNetWork();
    }

    @Override
    public void notNetWork() {
        super.notNetWork();
        statusView.showNoNetwork();
    }

    @Override
    public void showShopCarList(List<ShopCarEntity> list) {
        if (list.isEmpty()) {
            statusView.showEmpty();
            return;
        }
        statusView.showContent();

        adapter.focus.clear();
        int size = list.size();
        for (int i = 0; i < size; i++) {
            adapter.focus.add(false);
        }
        adapter.addDatas(list, true);
        getPrice();
    }

    public void getPrice() {
        amount = 0;
        count = 0;
        List<ShopCarEntity> shopCarEntities = adapter.getSelectProduct();
        if (shopCarEntities.isEmpty()) {
            amountView.setText("￥" + 0.0);
            if (isEditStatus) {
                sales.setBackgroundColor(getResources().getColor(R.color.color_E96056));
                sales.setText("删除");
            } else {
                sales.setBackgroundColor(getResources().getColor(R.color.color_0085B4));
                sales.setText("结算");
            }
            return;
        }
        DecimalFormat df = new DecimalFormat("######0.00");
        for (ShopCarEntity entity : shopCarEntities) {
            amount += entity.getDiscountedPrice() * entity.getItemCount();
            count += entity.getItemCount();
        }
        amountView.setText("￥" + df.format(amount));
        if (isEditStatus) {
            sales.setBackgroundColor(getResources().getColor(R.color.color_E96056));
            sales.setText("删除（" + count + "）");
        } else {
            sales.setBackgroundColor(getResources().getColor(R.color.color_0085B4));
            sales.setText("结算（" + count + "）");
        }
    }

    @Override
    public void showError() {
        statusView.showError();
    }

    @Override
    public void deleteSuccess() {
        presenter.getMyShopCar();
    }
}
